package com.example.casper.Experiment2024.gone;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.lifecycle.ViewModelProvider;

import android.app.AlertDialog;

import android.net.Uri;
import android.os.Bundle;

import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;

import android.widget.Toast;
import com.example.casper.Experiment2024.R;
import com.example.casper.Experiment2024.items.Location;
import com.example.casper.Experiment2024.items.locationSave;

import com.tencent.lbssearch.TencentSearch;
import com.tencent.lbssearch.httpresponse.BaseObject;
import com.tencent.lbssearch.httpresponse.HttpResponseListener;
import com.tencent.lbssearch.object.param.Geo2AddressParam;
import com.tencent.lbssearch.object.result.Geo2AddressResultObject;
import com.tencent.tencentmap.mapsdk.maps.CameraUpdate;
import com.tencent.tencentmap.mapsdk.maps.CameraUpdateFactory;
import com.tencent.tencentmap.mapsdk.maps.TencentMap;
import com.tencent.tencentmap.mapsdk.maps.TextureMapView;
import com.tencent.tencentmap.mapsdk.maps.model.BitmapDescriptorFactory;
import com.tencent.tencentmap.mapsdk.maps.model.CameraPosition;
import com.tencent.tencentmap.mapsdk.maps.model.LatLng;
import com.tencent.tencentmap.mapsdk.maps.model.Marker;
import com.tencent.tencentmap.mapsdk.maps.model.MarkerOptions;


import java.util.List;

public class TencentMapsFragment extends Fragment{
    private TextureMapView mapView, thumbnailMapView;
    private TencentMap tencentMap, thumbnailTencentMap;
    private Marker marker;
    private List<Location> locations;
    private OnLocationSelectedListener listener;
    private SharedViewModel sharedViewModel;

    public static TencentMapsFragment newInstance() {
        TencentMapsFragment fragment = new TencentMapsFragment();
        Bundle args = new Bundle();
        fragment.setArguments(args);
        return fragment;
    }
    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater,
                             @Nullable ViewGroup container,
                             @Nullable Bundle savedInstanceState) {
        View rootView = inflater.inflate(R.layout.fragment_tencent_maps, container, false);
        sharedViewModel = new ViewModelProvider(this).get(SharedViewModel.class);
        initializeMapViews(rootView);
//放缩
        Button zoomInButton = rootView.findViewById(R.id.zoomInButton);
        Button zoomOutButton = rootView.findViewById(R.id.zoomOutButton);

        zoomInButton.setOnClickListener(v -> tencentMap.animateCamera(CameraUpdateFactory.zoomIn()));
        zoomOutButton.setOnClickListener(v -> tencentMap.animateCamera(CameraUpdateFactory.zoomOut()));
//存储
        Button recordButton = rootView.findViewById(R.id.recordButton);
        LatLng point1 = new LatLng(22.255453, 113.54145);
        tencentMap.moveCamera(CameraUpdateFactory.newLatLngZoom(point1, 5));

        marker = tencentMap.addMarker(new MarkerOptions()
                .position(point1)
                .icon(BitmapDescriptorFactory.fromResource(R.drawable.qiqiu))
                .snippet("这是我要添加的位置")
                .draggable(true)
                .alpha(0.5f));

        recordButton.setOnClickListener(v -> showLocationInputDialog());
        return rootView;
    }


    private void initializeMapViews(View rootView) {
        mapView = rootView.findViewById(R.id.mapView);
        thumbnailMapView = rootView.findViewById(R.id.thumbnailMapView);

        if (mapView != null) {
            tencentMap = mapView.getMap();
            if(tencentMap!=null) {
                loadLocationMarkers();
                // 设置主地图的相机监听器
                tencentMap.setOnCameraChangeListener(new TencentMap.OnCameraChangeListener() {
                    @Override
                    public void onCameraChange(CameraPosition cameraPosition) {
                        // 主地图相机正在改变时, 更新缩略图的相机位置
                        updateThumbnailMap(cameraPosition);
                    }

                    @Override
                    public void onCameraChangeFinished(CameraPosition cameraPosition) {
                        // 相机改变完成时更新缩略图
                        updateThumbnailMap(cameraPosition);
                    }
                });
            }else{
                Log.e("TencentMapsFragment", "Main map is null.");
            }
        }
        if (thumbnailMapView != null) {
            thumbnailTencentMap = thumbnailMapView.getMap();
            if (thumbnailTencentMap != null) {
                thumbnailTencentMap.moveCamera(CameraUpdateFactory.zoomTo(15)); // 初始化缩略图的缩放级别
            }   else{
                Log.e("TencentMapsFragment", "thumbnail map is null.");
            }
        }
    }

    // 更新缩略图的相机位置
    private void updateThumbnailMap(CameraPosition cameraPosition) {
        // 设置缩略图与主地图的相机同步
        int zoomDifference = 3; // 缩略图比主地图低3个缩放级别（适当调整）
        CameraUpdate update = CameraUpdateFactory.newCameraPosition(
                new CameraPosition.Builder(cameraPosition)
                        .zoom(Math.min(cameraPosition.zoom - zoomDifference, 60)) // 限制缩略图的最大缩放级别
                        .build());

        if (thumbnailTencentMap != null) {
            thumbnailTencentMap.moveCamera(update);
        } else {
            Toast.makeText(getContext(), "Thumbnail map is still null", Toast.LENGTH_SHORT).show();
        }
    }


    private void loadLocationMarkers() {
        locations = getLocations();
        for (Location location : locations) {
            addMarker(location);
        }
    }
    private void showLocationInputDialog() {
        if (marker != null) {
            // 获取标记的经纬度
            LatLng latLng = marker.getPosition();

            // 创建感受输入框
            EditText inputFeeling = new EditText(getContext());
            inputFeeling.setHint("Enter your feeling");

            // 使用腾讯地图逆地理编码获取省市区信息
            TencentSearch tencentSearch = new TencentSearch(getContext());
            Geo2AddressParam geo2AddressParam = new Geo2AddressParam(latLng).getPoi(true)
                    .setPoiOptions(new Geo2AddressParam.PoiOptions()
                            .setRadius(1000) // 设置周边搜索半径
                            .setCategorys("面包") // 设置兴趣点类别（这里设置为“面包”）
                            .setPolicy(Geo2AddressParam.PoiOptions.POLICY_O2O)); // 设置 POI 策略

            // 逆地理编码请求
            tencentSearch.geo2address(geo2AddressParam, new HttpResponseListener<BaseObject>() {
                @Override
                public void onSuccess(int arg0, BaseObject arg1) {
                    if (arg1 == null) {
                        Toast.makeText(getContext(), "Failed to get location info", Toast.LENGTH_SHORT).show();
                        return;
                    }

                    Geo2AddressResultObject obj = (Geo2AddressResultObject) arg1;
                    String locationName = obj.result.address; // 获取省市区的完整地址
                    String province=obj.result.address_component.province;
                    // 创建对话框并显示位置和感受输入框
                    new AlertDialog.Builder(getContext())
                            .setTitle("New Location")
                            .setMessage("Location: " + locationName) // 显示获取的地址信息
                            .setView(inputFeeling) // 只显示感受输入框
                            .setPositiveButton("Save", (dialog, which) -> {
                                saveNewLocation(province,locationName, inputFeeling, latLng);
                            })
                            .setNegativeButton("Cancel", null)
                            .show();
                }

                @Override
                public void onFailure(int arg0, String arg1, Throwable arg2) {
                    Toast.makeText(getContext(), "Error: " + arg1, Toast.LENGTH_SHORT).show();
                }
            });
        } else {
            Toast.makeText(getContext(), "Marker is null", Toast.LENGTH_LONG).show();
        }
    }

    private void saveNewLocation(String province,String locationName, EditText inputFeeling, LatLng latLng) {
        String feeling = inputFeeling.getText().toString();

        if (!feeling.isEmpty()) {
            // 保存新位置
            Uri uri = Uri.parse("android.resource://" + getContext().getPackageName() + "/" + R.drawable.foot);
            Location newLocation = new Location(uri, locationName, latLng.latitude, latLng.longitude, feeling);
            newLocation.setProvince(province);
            locationSave databank = new locationSave(getContext());
            List<Location> locations = databank.readItems();
            locations.add(newLocation);
            databank.saveGoneItems(locations);

            // 通知 SharedViewModel 更新数据
            sharedViewModel.setListRefreshNeeded();

            Toast.makeText(getContext(), "Saved Location: " + locationName, Toast.LENGTH_LONG).show();
        } else {
            Toast.makeText(getContext(), "Please enter your feeling", Toast.LENGTH_LONG).show();
        }
    }

    private void addMarker(Location location) {
        MarkerOptions markerOptions = new MarkerOptions()
                .position(new LatLng(location.getLatitude(), location.getLongitude()))
                .title(location.getLocationName())
                .snippet(location.getFeeling())
                .icon(BitmapDescriptorFactory.fromResource(R.drawable.foot));

        tencentMap.addMarker(markerOptions);
    }

    private List<Location> getLocations() {
        locationSave databank = new locationSave(getContext());
        return databank.readItems();
    }



    @Override
    public void onStart() {
        super.onStart();
        if (mapView != null) mapView.onStart();
    }

    @Override
    public void onResume() {
        super.onResume();
        if (mapView != null) {
            mapView.onResume();
        }
        if (thumbnailMapView != null) {
            thumbnailMapView.onResume();
        }
    }

    @Override
    public void onPause() {
        super.onPause();
        if (mapView != null) {
            mapView.onPause();
        }
        if (thumbnailMapView != null) {
            thumbnailMapView.onPause();
        }
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        if (mapView != null) {
            mapView.onDestroy();
        }
        if (thumbnailMapView != null) {
            thumbnailMapView.onDestroy();
        }
    }
    @Override
    public void onDestroy() {
        super.onDestroy();
        if (mapView != null) mapView.onDestroy();
        if (thumbnailMapView != null) thumbnailMapView.onDestroy();
    }

    @Override
    public void onStop() {
        super.onStop();
        if (mapView != null) mapView.onStop();
        if (thumbnailMapView != null) thumbnailMapView.onStop();
    }



    public interface OnLocationSelectedListener {
        void onLocationSelected(Location location);
    }
}

